/*
Cogumelo v0.2 - Innoto S.L.
Copyright (C) 2010 Innoto Gestión para el Desarrollo Social S.L. <mapinfo@map-experience.com>

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
USA.
*/

// NOTA: Este ficheiro non foi revisado para a revisión 0.2 de Cogumelo

//
// Table
// ( Loads data from ajax and JSON)
//
var Table = Class
		.create({
			init : function(TableID, options) {
				
				this.id = TableID;
				this.container = $('#'+TableID + 'Container');
				this.data = null;
				this.firstLoad = true;
				this.currentCommand = null;
				this.options = $.extend( {
					url : false, // url JSON data
					formUrl : "",
					onloadForm : false
				}, options || {});
				this.container.html('');
				intval = '';
				var that = this;
				
				this.LoadData('getdata');
				
				// function to handle the data coming back from the history upon forw/back hit
				
				$.history.callback = function ( reinstate, cursor ) {
					
					// check to see if were back to the beginning without any stored data
					if (typeof(reinstate) == 'undefined'){
						that.init(that.id,that.options);
					}
					else{
						
						that.container.html('');
						if (reinstate.elementid){
							that.FormLoad(reinstate.elementid);
						}
						else
							that.init(that.id,that.options);
						}
				}
			
				this.Refresh();
			},
			
	
			FormLoad : function(itemId) {
				var that = this;
				if (this.options.formUrl!="") {
					// if periodical search is runing stop it
					if (intval)
						clearInterval(intval);
					if (this.options.param!=false)
						var par = this.options.param;
					
					if (itemId!='')
						var url = this.options.formUrl + '&id=' + itemId;
					else
						var url = this.options.formUrl;
						
					
					this.container.load(url, function(response, status, xhr){
						if (status=='success'){
							$.history({'elementid' : itemId});
							if (that.options.onloadForm != false)
								that.options.onloadForm();	
						}
					});		
				}
				
			},
		

			TableWrite : function() {
				
				this.CreateTable();
				// Table Controls
				if (this.firstLoad == true)
					this.CreateControls();
				
				if (this.data != null) {
					// Create Table Header
					this.CreateHeaders();
				}
				var that = this;	
				// Create Rows
				
				if (this.data.Data != null) {
					$.each(this.data.Data,function(index, item) {
						that.AddRow(item, index);
					});
				}
				
				// Page info
				this.PrintPageInfo();	
				
				// show Tabs
				this.showTabs();
				
				// show Filters
				this.showFilters();
				
				// Create table Events
				this.createObservers();
				
				this.firstLoad = false;
			},
			
			//
			// Load JSON data from url
			//
			LoadData : function(command) {
				var that = this;
				$.ajax({
					async : false,
					url : this.options.url + '&cmd=' + command,
					encoding : 'UTF-8',
					dataType: 'json',
					success : function(transport) {
						that.data = transport;
					}
				});

			},
			
			//
			//	Refresh table
			//
			Refresh: function()	{
				this.TableWrite();	
				$.history({'elementid' : ''});
			},
			
			//
			// Add new row to table
			//
			AddRow : function(rowObj, index) {
	
				var rowObj = rowObj;

				var rowData = new Array();
				var i=0;
				if (rowObj != null){
					$.each(rowObj,function(index, item){
						rowData[i] = item;
						i++;
					});
	
					var rowid;
	
					// pair row (for color)
					if ((index % 2) == 0)
						var ispair = 'pair';
					else
						var ispair = 'unpair';
					var tr = $('<tr>',{
						id: 3,
						'class' : ispair
					});
	
					var firstTD = true;
					var that = this;
					$.each(rowData, function(index, item) {
						if (firstTD == true) {
							if (that.data.options.multiselect == true) {
								tr.attr('id', 'rowdb_' + item);
								tr.append($('<td>', {
									id : 'slctrow_' + item,
									'class' : 'edit'
								}).html('<input type="checkbox" value=true>'));
							}
							
							// if showID is true (show id cell)
							if(that.data.options.showID == true)
								tr.append($('<td>').html(item));
						} else
							tr.append($('<td>').html(item));
						firstTD = false;
					});
				}	
				$('#'+this.id + 'AjaxTable tbody').append(tr);
			
				
			},

			
			//
			// Create Table Structure into container
			//
			CreateTable : function() {
				if (this.firstLoad == true) {
					// insert controls row
					this.container
							.prepend('<div id="' + this.id + '_controls" class="AjaxTableControls"></div>');
					// insert tabs row
					this.container
							.prepend('<div id="' + this.id + '_tabs" class="AjaxTableTabs"></div>');
					// insert fix commands
					this.container
							.prepend('<div id="' + this.id + '_fixcommands" class="AjaxTableFixCmds"></div>');

				} else {
					$('#'+this.id + '_tb').remove();
					// this.container.update();
				}
				
				var Tabl = $('<div id="'+ this.id +'_tb"></div>');

				Tabl.prepend('<table  id="' + this.id + 'AjaxTable" class="AjaxTable"><thead></thead><tbody></tbody></table>');
				Tabl.append('<div id="' + this.id + '_pager" class="AjaxTablePager"></div>');

				Tabl.appendTo(this.container);
			},

			//
			// Create Table Headers
			//
			CreateHeaders : function() {
				var hdrs = this.data.headers;
				var tr = $('<tr>',{});
				var firstLoad = true;
				var that = this;
				
				if (hdrs != false){
					$.each(hdrs,function(index, item) {
					
						if (firstLoad == true){
							tr.append($('<td>', {
								'id' : item.id + ''
							}).html(''));
						
							// if showID is true (show id cell)
							if(that.data.options.showID == true)
								tr.append($('<td>', {
									'id' : item.id + ''
								}).html(item.name + that.OrderPicture(item.order)));
						
						}
						else
							tr.append($('<td id="' + item.id + '">').html(item.name + that.OrderPicture(item.order)));
						firstLoad = false;
					});
				}
				$('#'+this.id + 'AjaxTable thead').append(tr);
			},
		
			//
			// Create Table Controls
			//
			CreateControls : function(firstLoad) {
				// comboboxes
				if (this.data.filters.comboboxes)	{
					that = this;
					$.each(this.data.filters.comboboxes ,function(i, e) {
						$('#' + that.id + '_controls').prepend($('<select id="combo' + i + '" class="tablecombo" ></select>'));
						var comboid = 'combo' + i;
						var selectid = e.selectid;
						$.each(e.list ,function(i, e) {
							 if(i == selectid)	 var sel = "SELECTED";
							 else				 var sel ="";
							$('#' + comboid).append('<option '+ sel +' value="' + i + '">' + e + '</option>');
						});
					});
				}
				// find control
				if (this.data.options.find == true)	
					$('#' + this.id + '_controls').prepend($('<input id="' + this.id + 'Find" class="searchReady" value=""></input>'));
				
				
				// command controls span
				$('#' + this.id + '_controls').append('<span id="' + this.id + 'Commands"></span>');
			},

			//
			// Print page info
			// (number of pages and aditional information)
			//
			PrintPageInfo : function() {
				var nextBtn = ' <span id="' + this.id + 'NextPage" class="AjaxTableBTN" >Siguiente</span>';
				var prevBtn = '<span id="' + this.id + 'PrevPage" class="AjaxTableBTN" >Anterior</span> ';

				$('#' + this.id + '_pager').prepend('<div id="pager">' + prevBtn + '&emsp;pág.&emsp;' + this.data.Info.page + ' / '+ this.data.Info.pages + '&emsp;<span class="totregs">(' + this.data.Info.totalregs + '&emsp;registros)</span>&emsp;' + nextBtn + '</div>');
				
			},
	
			//
			// Delete all table
			// show header cell order picture (up or down)
			//
			OrderPicture : function(ord) {

				if (ord > 0)
					return '<span class="OrdUp">&nbsp;&nbsp;&nbsp;&nbsp; </span>';
				else if (ord < 0)
					return '<span class="OrdDown">&nbsp;&nbsp;&nbsp;&nbsp; </span>';
			},
	
			setSelectedRow : function(row) {
				if ($(row).hasClass('selected')) {
					// mark as unselected
					$(row).removeClass('selected');
				} else {
					// mark as selected
					$(row).addClass('selected');
				}
			},
			
			showTabs : function() {

				if (this.data.options.tabs != false) {
					var tabs = '<ul>';
					var tabCommands;
					
					var currentSel = this.data.filters.status;
					
					$.each(this.data.options.tabs, function(index, item) {
						// if is selected tab
							if (currentSel == item.id)
								var clss = "selected";
							else
								var clss = ""
							tabs = tabs + '<li class="' + clss + '" id="tab_'
									+ item.id + '">' + item.name + '</li>';
						});

					tabs = tabs + '</ul>';

					// print Tabs
					$('#' + this.id + '_tabs').html('<div id="new_' + this.id
							+ '" class="new">Nuevo</div>');
					$('#' + this.id + '_tabs').append(tabs);

					// fix table commands
					$('#' + this.id + '_fixcommands').html('');
					var thus = this;
					$.each(this.data.options.tabs, function(index, item){
							if (item.id == currentSel){
								if(item.fixactions) {
									$.each(item.fixactions, function(i, e){
										$('#' + thus.id + '_fixcommands').prepend('<a href="'+e.url+'"><img title="'+e.title+'" class="fixcommandBTN" src="Templates/images/'+e.icon+'" border="none"/></a>');
									});
								}
							}
					});
					
					// asign Tab events
					if(this.data.options.tabs){
						$.each(this.data.options.tabs, function(index, item) {
							$('#tab_' + item.id).click(function(e){
								var tab = $(e.target);
								thus.LoadData('tabSet&tab=' + tab.attr('id').substring(4, 20));
							});
						});
					}	
					//
					// Show command tabs
					//
					// look for the tab commands
					if(this.data.options.tabs){
						$.each(this.data.options.tabs, function(index, item) {
							if (item.id == currentSel)
								tabCommands = item.commands;
						});
					}
			
					// Print commands
					$('#' + this.id + 'Commands').html('');

					$.each(tabCommands, function(index, item) {
						
						$('#' + thus.id + 'Commands').append($('<a id="command_' + item.id + '" >' + item.name + '</a> '));
						
						// asign command events
						$('#command_' + item.id).bind('click', function(e){						
							var cmd = $(e.target);
							if (thus.currentCommand){
								$.each(thus.currentCommand, function(index, item) {	
									if (cmd.attr('id').substring(8, 20) == item.id){
										thus.LoadData(item.command + '&items='+ thus.getSelectedRows());
										thus.Refresh();
									}
								});
							}
						});
					});
					this.currentCommand = tabCommands;
					
				}
				
			},

			showFilters : function() {		
				
				// Search input
				if (this.data.options.find == true) {
					if (this.data.filters.find == false) {
						if (this.firstLoad){
							$('#' + this.id + 'Find').val('Buscar...');
							
						}
					} else{
						if (this.data.filters.find != 'undefined')
							$('#' + this.id + 'Find').val(this.data.filters.find);
					}
				}
				
			},
			
					
			getSelectedRows : function() {
				var rowsList = "";
				var comma = "";

				var row = $('#' + this.id + 'AjaxTable tbody tr');
				
				if (row != null){
					$.each(row, function(index, item){
						if ($(item).hasClass('selected')) {
							rowsList = rowsList + comma + item.id.substring(6, 20);	
							comma = ",";
						}
					});
				}
					
				return rowsList;

			},
	
			//
			//
			// EVENTS
			//
			//

			createObservers : function() {
				var tabl = this.id;
				var that = this;
				
				// Row Click
				$('#' + tabl + 'AjaxTable tbody tr').bind('click', function(e){
					var elm = $(e.target);	
					if (elm.parentsUntil('tbody').attr('id').substring(0, 7) == 'slctrow') {
						that.setSelectedRow(elm.parentsUntil('tbody')[1]);
					}
					else{
						that.FormLoad(elm.parent().attr('id').substring(6, 20));
					}
				});
			
				// Header Click
				$('#' + tabl + 'AjaxTable thead tr').bind('click', function(e){
					var trHead = $(e.target);
					that.LoadData('orderby&headerid=' + trHead.attr('id'));
					that.Refresh();
				});
				
				// Table Pager
				$('#' + tabl + 'NextPage').bind('click', function(){
					that.nextPage(that);
				});
				$('#' + tabl + 'PrevPage').bind('click', function(){
						that.prevPage(that);
				});

				// New element
				$('#new_' + this.id).bind('click', function(){
						that.FormLoad('');
				});

				// Find actions
				if (this.data.options.find == true) // if find element exist
				{
					// find click
					$('#' + this.id + 'Find').bind('click', function(){
						that.findClick(that);
					});
					
					this.previousFindValue = $('#' + this.id + 'Find').val();
					
					if (!intval){
						intval = self.setInterval(function(){that.findAction();} ,2000);
					}
				}

				// Combobox filter selectors
				if (this.data.filters.comboboxes) {
					if(this.firstLoad){
						$.each(this.data.filters.comboboxes ,function(i, e) {
							$('#combo' + i).bind('change', function(){
								that.LoadData('setcomboboxes&comboboxid='+ i +'&value=' + $('#combo' + i).attr('value'));
								that.Refresh();
							});
						});
					}
				}
			},
	
			setPage : function(page) {
				this.LoadData('pageset&page=' + page);
				this.Refresh();
			},

			nextPage : function() {
				this.LoadData('pagenext');
				this.Refresh();
			},

			prevPage : function() {
				this.LoadData('pageprev');
				this.Refresh();
			},

			// Find methods
			findClick : function() {
				$('#' + this.id + 'Find').val('');
			},
			
			findAction : function() {
				if (!$('#' + this.id + 'Find'))
					return 0;

				var Stamp = new Date();

				var actualTime = Stamp.getHours().toString()
						+ Stamp.getSeconds().toString();

				// console.log(this.findLastChange + ' check ' + actualTime);
					// this.timerSwitch == 'on'
		
					if (this.findLastChange < (actualTime - 1) && intval) {	
						this.LoadData('find&term=' + $('#' + this.id + 'Find').val());
						this.Refresh();
						
						// / Aparence
						$('#' + this.id + 'Find').removeClass('searching');
						$('#' + this.id + 'Find').addClass('searchReady');
	
						this.findLastChange = actualTime;
						intval = clearInterval(intval);
						
						//this.timerSwitch = 'off';
					}
					var that = this;
					
					if ($('#' + this.id + 'Find').val() != this.previousFindValue) {
				
						var that = this;
						this.findLastChange = actualTime;
						//this.timerSwitch = 'on';
						intval = self.setInterval(function(){that.findAction();} ,2000);
						
						// / Aparence
						$('#' + this.id + 'Find').removeClass('searchReady');
						$('#' + this.id + 'Find').addClass('searching');
					}
					this.previousFindValue = $('#' + this.id + 'Find').val();
			
			}
			
		});